#include <SoftwareSerial.h>


#include "WProgram.h"
void setup();
void loop();
SoftwareSerial softserial(6, 5);
int RxLCD = 6;
int TxLCD = 5;
int ledPin = 13;                // choose the pin for the LED
int EncCHA = 10;                // choose the input pin (for a pushbutton)
int EncCHB = 11;                // choose the input pin (for a pushbutton)
int val = 0;                    // variable for reading the pin status
int wasLOW=0;
int EncValue = 0;
int EncPulse = 1;
int EncDivider = 0;
int EncDividerCountUP = 0;
int EncDividerCountDW = 0;


void setup()
{
//Config of the rotary encoder
pinMode(EncCHA, INPUT);
pinMode(EncCHB, INPUT);
pinMode(ledPin, OUTPUT);      // declare LED as output
pinMode(TxLCD, OUTPUT);
digitalWrite(TxLCD, HIGH);
delay (100);
softserial.begin(9600);
delay (100);
softserial.print(22, BYTE); // turn on LCD, No Cursor
softserial.print(17, BYTE); // turn on back light
delay (50);
softserial.print(12, BYTE); // Clear Screen
softserial.print(" DMX Console V1.0");
delay (1000);
softserial.print(12, BYTE); // Clear Screen
delay (50);
softserial.print("DMX Channel:000");


}

void loop()
{
  val = digitalRead(EncCHA);  // read input value
  if (val == HIGH ) 
    {    // check if the input is HIGH
    if (wasLOW)
      {
      if (digitalRead(EncCHB))
        { 
        // Up Direction High Speed  
        if (++EncDividerCountUP > EncDivider)
          {
          EncDividerCountUP=0;
          EncValue++;
            if (EncValue >512)
              EncValue = 512;  
          }
        }
      if (!digitalRead(EncCHB))
        {
        // Down direction  
        if (++EncDividerCountDW > EncDivider)
          {
          EncDividerCountDW = 0;  
          if (EncValue)
            EncValue--;  
          }        
        }
      digitalWrite(ledPin, LOW);  // turn LED OFF
      wasLOW=0;
      EncPulse =1;
      }
    } 
  if (val == LOW) 
    {
    wasLOW = 1;
    digitalWrite(ledPin, HIGH); // turn LED ON
    }
if (EncPulse)
  {
  EncPulse=0;
  softserial.print(0x8C, BYTE);
  if (EncValue<100)
    softserial.print('0');
  softserial.print(EncValue);
  }
  // print it out in many formats:
  //serial.print("B");         // print as an ASCII-encoded decimal
  
  // delay 10 milliseconds before the next reading:
  
} 

int main(void)
{
	init();

	setup();
    
	for (;;)
		loop();
        
	return 0;
}

